import { createStore } from "vuex";
import createPersistedState from "vuex-persistedstate";

import { routes } from "@/router";

// const username = localStorage.getItem("username");

/**
 * 过滤当前用户有权限的路由集合
 * @param {*} routes 路由规则表数据
 * @param {*} roles 当前用户的权限集合 ['home']
 */
function filterRoutes(routes, roles) {
  // 最终返回结果
  let result = [];
  routes.forEach((route) => {
    // 拷贝一份对象
    const tmp = { ...route };
    if (roles.includes(tmp.name)) {
      // 是否有 children
      if (tmp.children) {
        tmp.children = filterRoutes(tmp.children, roles);
      }

      result.push(tmp);
    }
  });

  return result;
}

const store = createStore({
  state: {
    // 登录用户名
    username: "",
    // 页面权限: ['home', 'banner-list', 'banner']
    pageRoles: [],
    // 用户角色 1 - 管理员  2 - 超级管理员
    role: "",
    sex: "",
    // 左侧菜单是否收起
    isFold: false,
  },

  getters: {
    /**
     * 当前用户有权限访问的路由页面routes
     */
    permissionRoutes(state) {
      //console.log("hello");
      const arr = routes.filter((item) => !item.hidden);
      if (state.role === 2) {
        // 超级管理员
        return arr;
      } else {
        // 普通管理员
        return filterRoutes(arr, state.pageRoles);
      }
    },
  },

  mutations: {
    setUsername(state, username) {
      state.username = username;

      // localStorage.setItem("username", username);
    },

    setState(state, payload) {
      state.username = payload.adminname;
      state.pageRoles = payload.checkedkeys;
      state.role = payload.role;
    },

    toggleIsFold(state) {
      state.isFold = !state.isFold;
    },
  },

  plugins: [
    createPersistedState({
      // 额外配置
      // 指定本地存储使用什么： 默认是 window.localStorage
      // storage: window.sessionStorage,
      // 指定只对那些 state 做存储, 默认是 全部存储
      // reducer: (state) => {
      //   return {
      //     username: state.username,
      //   };
      // },
    }),
  ],
});

export default store;
